import { defineStore } from 'pinia';
import { ref, reactive } from 'vue';
import router from '@/router/index';

export const useLoadingStore = defineStore('loading', {
  state: () => {
    return {
      loading: ref(false),
    };
  },
  actions: {
    setLoading(status) {
      this.loading = status;
    },
  },
});

// 设置tab
export const pageTabsStore = defineStore('hanelTab', {
  state: () => {
    return {
      tabList: reactive([]),
    };
  },
  actions: {
    setTab(tab) {
      if (tab) {
        const obj = {
          title: tab.title || '',
          name: tab.name || '',
          path: tab.path || '',
          keepAlive: tab.keepAlive || '',
        };
        const repeatIndex = this.tabList.findIndex((v) => {
          return v.name === obj.name;
        });
        if (repeatIndex === -1) {
          this.tabList.push(obj);
        }
      }
    },
    deleteTab(tab) {
      const list = this.tabList;
      const delIndex = this.tabList.findIndex((v) => {
        return v.name === tab;
      });
      if (delIndex !== -1) {
        const toIndex = delIndex - 1;
        list.splice(delIndex, 1);
        this.tabList = list;
        if (toIndex === -1) {
          // Router.replace('/home');
        } else {
          router.replace(list[toIndex].path);
        }
      }
    },
    deleteAllTab() {
      this.tabList = [];
    },
  },
  persist: {
    enabled: true,
  },
});

// 用户信息
export const userInfoStore = defineStore('getUser', {
  state: () => {
    return {
      userInfo: reactive({}),
      userMenuList: reactive([]),
    };
  },
  actions: {
    getUserInfo(info) {
      this.userInfo = info;
    },
    setMenu(list) {
      this.userMenuList = list;
    },
  },
  persist: {
    enabled: true,
  },
});
